# coding=utf-8

import datetime

from rest_framework import serializers

from account.seriailzers import UserSer
from utils import pretty
from utils.date_scraper import get_datetime_from_stamp
from .models import Comment


class CommentSer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = "__all__"


class CommentUpdateSer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = "__all__"
        extra_kwargs = {
            'source': {'read_only': True},
            'object_id': {'read_only': True},
            'creater': {'read_only': True},
            'comment': {'read_only': True},
            'comment_to': {'read_only': True},
            'comment_to_user': {'read_only': True},
        }


class CommentDetailSer(serializers.ModelSerializer):
    creater = serializers.SerializerMethodField()
    content = serializers.SerializerMethodField()
    pretty_time = serializers.SerializerMethodField()
    title = serializers.SerializerMethodField()
    comment_to_user = serializers.SerializerMethodField()
    created_time = serializers.SerializerMethodField()

    class Meta:
        model = Comment
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        try:
            self.user_id = kwargs.pop('user_id')
        except:
            self.user_id = 0
        super(CommentDetailSer, self).__init__(*args, **kwargs)

    def get_creater(self, obj):
        return UserSer(obj.creater).data

    def get_content(self, obj):
        if obj.comment_to:
            if obj.comment_to.id == self.user_id:
                obj.content = ("@我: %s" % (obj.content))
            else:
                if obj.source == 'topic':
                    obj.content = ("@%s: %s" % (obj.comment_to.creater.zsxm, obj.content))
        return obj.content

    def get_pretty_time(self, obj):
        return pretty.date(datetime.datetime.fromtimestamp(obj.created_time))

    def get_title(self, obj):
        creater = obj.creater.zsxm
        content = ""
        if obj.comment_to != None:
            content = u"你的评论"
        return u"%s回复了%s" % (creater, content)

    def get_created_time(self, obj):
        return get_datetime_from_stamp(obj.created_time)

    def get_comment_to_user(self, obj):
        return UserSer(obj.comment_to_user).data
